package com.jl.utils;

import com.alibaba.fastjson.JSONObject;
import com.jl.enums.ReadyStatus;
import com.jl.enums.RoomAction;
import com.jl.model.req.RoomIntoReq;
import com.jl.model.resp.RoomInfoResp;
import com.jl.model.socket.MyChannelHandlerPool;
import com.jl.model.socket.RoomDetail;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Map;

public class MySocketUtil {

    /*
    判断过程是否完成
     */
    public static boolean finish(RoomDetail roomDetail, String property) {
        Map<Integer, Object> userInfo = roomDetail.getUserInfo();
        boolean a = true;
        Collection<Object> values = userInfo.values();
        for (Object value : values) {
            try {
                if ("bets".equals(property)&&"1".equals(PropertyUtils.getProperty(value,"banker"))){ //如果是抢庄则特殊处理, 庄家不需要下注
                    continue;
                }
                if (ReadyStatus.type3.getId().equals(PropertyUtils.getProperty(value,"ready"))){
                    continue;
                }
                if (PropertyUtils.getProperty(value,property)==null || ("status".equals(property)&&"0".equals(PropertyUtils.getProperty(value,"status")))){
                    a = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    /*
    发送信息给房间所有人
     */
    public static void sendRoomAllMessage(String message,RoomDetail roomDetail){
        MyChannelHandlerPool player = roomDetail.getPlayer();
        MyChannelHandlerPool watcher = roomDetail.getWatcher();
        player.getChannelGroup().writeAndFlush(new TextWebSocketFrame(message));
        watcher.getChannelGroup().writeAndFlush(new TextWebSocketFrame(message));
    }

    /*
    发送观战信息给房间所有人
     */
    public static void sendWatchCount(RoomIntoReq roomIntoReq, RoomDetail roomDetail){
        RoomInfoResp roomInfoResp = new RoomInfoResp();
        BeanUtils.copyProperties(roomIntoReq,roomInfoResp);
        roomInfoResp.setAction(RoomAction.type0.getId());
        roomInfoResp.setActionValue(String.valueOf(roomDetail.getWatcher().getChannelGroup().size()));
        roomInfoResp.setUserId(null);
        roomInfoResp.setSeat(null);
        MySocketUtil.sendRoomAllMessage(JSONObject.toJSONString(roomInfoResp),roomDetail);
    }

    public ChannelFuture clientConnect(Class<? extends ChannelInboundHandlerAdapter> clazz) throws InterruptedException {
        // 首先，netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();

        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group );

        //第2步 绑定客户端通道
        client.channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<NioSocketChannel>() {  //通道是NioSocketChannel
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //字符串编码器，一定要加在SimpleClientHandler 的上面
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(
                                Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
                        //找到他的管道 增加他的handler
                        ch.pipeline().addLast(clazz.newInstance());
                    }
        });

        //连接服务器
        ChannelFuture future = client.connect("localhost", 8888).sync();
        return future;
    }

    public static void main(String[] args) throws URISyntaxException {
        String a = "ws://localhost:8888/ws";
        URI uri = new URI(a);
        System.out.println(uri.getHost());
    }
}
